package com.example.lemis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.lemis.mapper.FkBannerDivisionMapper;
import com.example.lemis.model.domain.Banner;
import com.example.lemis.mapper.BannerMapper;
import com.example.lemis.model.dto.BannerDTO;
import com.example.lemis.model.dto.PageDTO;
import com.example.lemis.service.IBannerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-06-24
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements IBannerService {
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMM");

    @Value("${file-upload-path}")
    private String fileUploadPath;

    @Autowired
    private BannerMapper bannerMapper;

    @Autowired
    private FkBannerDivisionMapper fkBannerDivisionMapper;

    @Override
    public Map upload(MultipartFile file){
        Map<String, String> map = null;
        try {
            map = storeFile(file, Paths.get(fileUploadPath, "image").toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    @Override
    public Banner add(Banner banner) {
        bannerMapper.insert1(banner);
        LambdaQueryWrapper<Banner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Banner::getId, banner.getId());
        return bannerMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public Page<BannerDTO> BannerList(BannerDTO bannerDTO, PageDTO pageDTO) {
        Page<BannerDTO> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        page = bannerMapper.BannerList(page, bannerDTO);
        return page;
    }

    private static Map<String, String> storeFile(MultipartFile file, String fileUploadPath) throws IOException {

        String yearMonth = SDF.format(new Date());//当前年月
        String fileName = file.getOriginalFilename();//文件全名
        String suffix = suffix(fileName);//文件后缀
        String relPath = "/" + yearMonth + "/" + "-" + UUID.randomUUID().toString().replaceAll("-","") + suffix;
        String toPath = fileUploadPath + relPath;
        FileOutputStream out = null;

        File toFile = new File(toPath).getParentFile();
        if (!toFile.exists()) {
            toFile.mkdirs(); //自动创建目录
        }
        try {
            out = new FileOutputStream(toPath);
            out.write(file.getBytes());
            out.flush();
            Map<String, String> map = new HashMap();
            map.put("url", "/image" + relPath);
            return map;
        } catch (FileNotFoundException fnfe) {
            throw fnfe;
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 后缀名或empty："a.png" => ".png"
     */
    private static String suffix(String fileName) {
        int i = fileName.lastIndexOf('.');
        return i == -1 ? "" : fileName.substring(i);
    }
}
